package com.sitia.jd.util;

import com.sitia.common.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.Map;

/**
 * 通用工具类
 */
@Slf4j
public class CommonUtils {
    public static File downloadJdLoginQRCode(String fileName, String testUrl)  {


        CloseableHttpClient httpClient = HttpClients.createDefault();
        //获取url链接
        String url = "https://qr.m.jd.com/show?appid=133&size=147&t=()";
        HttpPost post = new HttpPost(url);
        post.setEntity(new StringEntity("referer","https://passport.jd.com/"));
        post.setEntity(new StringEntity("Connection","keep-alive"));
        post.setEntity(new StringEntity("Accept-Language","zh-CN,zh;q=0.9"));
        File file = null;
        System.out.println(url);
        String downloadFileName = null;
        try (CloseableHttpResponse response = httpClient.execute(post)) {
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {


                String tempDir = System.getProperty("java.io.tmpdir");
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    String contentType = entity.getContentType().getValue();
                    if (contentType.equals("application/json;charset=UTF-8")) {
                        String json = EntityUtils.toString(entity, "UTF-8");
                        throw new CustomException(json);
                    } else{

                        Header[] headers = response.getHeaders("Content-Disposition");
                        Header header = headers.length > 0 ? headers[0] : null;
                        if (header != null) {
                            String headerName = header.toString();
                            String[] filenames = headerName.split("filename");
                            String filename =  URLDecoder.decode(filenames[1],"UTF-8");
                            downloadFileName = filename.substring(filename.indexOf('=') + 1).trim().replace("\"", "");
                            System.out.println("下载文件名" +downloadFileName);
                        }

                        //String[] contentDisposition = headers != null ? headers.split(";") : new String[]{};
                        /*for (String value : contentDisposition) {

                        }*/


                        InputStream in = entity.getContent();

                        File tempFile = new File(tempDir, downloadFileName==null?fileName+".png":downloadFileName);

                        // 将InputStream中的数据写入到临时文件中
                        OutputStream outputStream = Files.newOutputStream(tempFile.toPath());
                        byte[] buffer = new byte[1024];
                        int length;
                        while ((length = in.read(buffer)) != -1) {
                            outputStream.write(buffer, 0, length);
                        }
                        // 关闭输入流和输出流
                        in.close();
                        outputStream.close();
                        // 将临时文件转换为File对象

                        file = new File(tempFile.getAbsolutePath());
                        log.info("QRCodePath: " + file.getAbsolutePath());
                        return file;
                    }
                    /* }*/
                } else {
                    String rest = response.getEntity().toString();
                    throw new CustomException(rest);
                }
            }


        } catch (IOException e) {
            log.error("文件下载失败，路径是" + url);
            throw new CustomException("下载文件失败");
        }

        log.info("文件下载完成");
        return file ;
    }
}
